package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.ruoyi.common.core.domain.entity.SysUser;
import net.lingala.zip4j.model.ZipParameters;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ElevatorInfo;
import com.ruoyi.system.service.IElevatorInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
/**
 * 电梯信息Controller
 * 
 * @author ruoyi
 * @date 2023-12-17
 */
@RestController
@RequestMapping("/system/info")
public class ElevatorInfoController extends BaseController
{
    @Autowired
    private IElevatorInfoService elevatorInfoService;

    /**
     * 查询电梯信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:info:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElevatorInfo elevatorInfo)
    {
        startPage();
        List<ElevatorInfo> list = elevatorInfoService.selectElevatorInfoList(elevatorInfo);
        return getDataTable(list);
    }
    /**
     * 同步电梯数据
     */
    @PreAuthorize("@ss.hasPermi('system:info:sync')")
    @GetMapping("/sync")
    public AjaxResult sync()
    {
        return elevatorInfoService.sync();
    }
    /**
     * 同步电梯数据
     */
    @GetMapping("/syncHis")
    public AjaxResult syncHis()
    {
         elevatorInfoService.hisElevatorInfo();
         return success();
    }

    /**
     * 导出电梯信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:info:export')")
    @Log(title = "电梯信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElevatorInfo elevatorInfo)
    {
        List<ElevatorInfo> list = elevatorInfoService.selectElevatorInfoList(elevatorInfo);
        list.forEach(x->{
            x.setQrcode("RESID:"+x.getDTBH()+",EQULOGCODE:"+x.getSBZCDM());
        });
        ExcelUtil<ElevatorInfo> util = new ExcelUtil<ElevatorInfo>(ElevatorInfo.class);
        util.exportExcel(response, list, "电梯信息数据");
    }
    @PreAuthorize("@ss.hasPermi('system:info:export')")
    @Log(title = "电梯信息", businessType = BusinessType.EXPORT)
    @PostMapping("/exportFile")
    public void exportFile(HttpServletResponse response, Long[] elevatorIds) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        List<ElevatorInfo> list = elevatorInfoService.selectElevatorInfoByElevatorIds(elevatorIds);
        List<ElevatorInfo> tempList=new ArrayList<>();
        List<ElevatorInfo> finalTempList = tempList;
        list.forEach(x->{
            ElevatorInfo elevatorInfo=new ElevatorInfo();
            elevatorInfo.setSBZCDM(x.getSBZCDM());
            elevatorInfo.setQrcode(x.getQrcode());
            elevatorInfo.setDTBH(x.getDTBH());
            finalTempList.add(elevatorInfo);
        }
        );
        tempList=finalTempList.stream().filter(distinctByKey(x->x.getDTBH())).collect(Collectors.toList());
        tempList.forEach(x->{
            x.setQrcode("RESID:"+x.getDTBH()+",EQULOGCODE:"+x.getSBZCDM());
            byte[] qrCodeBytes = generateQRCode("http://jc.amr.guizhou.gov.cn:7809/scdeap/DTQR/"+x.getSBZCDM(), 300, 300);
            ZipEntry entry = new ZipEntry( x.getDTBH() + ".png");
            try {
                zipOutputStream.putNextEntry(entry);
                zipOutputStream.write(qrCodeBytes);
                zipOutputStream.closeEntry();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        zipOutputStream.flush();
        zipOutputStream.close();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=qr_codes.zip");
        try {
            response.getOutputStream().write(outputStream.toByteArray());
            response.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
            // Handle exception
        }
    }
    <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
    byte[] generateQRCode(String text, int width, int height) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
        } catch (WriterException | IOException e) {
            e.printStackTrace();
            // Handle exception
        }
        return outputStream.toByteArray();
    }
    byte[] compressToZip(List<byte[]> qrCodeBytesList) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
            for (int i = 0; i < qrCodeBytesList.size(); i++) {
                byte[] qrCodeBytes = qrCodeBytesList.get(i);
                ZipEntry entry = new ZipEntry("qr_code_" + i + ".png");
                zipOutputStream.putNextEntry(entry);
                zipOutputStream.write(qrCodeBytes);
                zipOutputStream.closeEntry();
            }
        } catch (IOException e) {
            e.printStackTrace();
            // Handle exception
        }
        return outputStream.toByteArray();
    }

    /**
     * 获取电梯信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:info:query')")
    @GetMapping(value = "/{elevatorId}")
    public AjaxResult getInfo(@PathVariable("elevatorId") Long elevatorId)
    {
        return success(elevatorInfoService.selectElevatorInfoByElevatorId(elevatorId));
    }

    /**
     * 新增电梯信息
     */
    @PreAuthorize("@ss.hasPermi('system:info:add')")
    @Log(title = "电梯信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElevatorInfo elevatorInfo)
    {
        return toAjax(elevatorInfoService.insertElevatorInfo(elevatorInfo));
    }

    /**
     * 修改电梯信息
     */
    @PreAuthorize("@ss.hasPermi('system:info:edit')")
    @Log(title = "电梯信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElevatorInfo elevatorInfo)
    {
        if(elevatorInfo.getNfcid()=="")
        {
            return AjaxResult.error("NFCID不能为空");
        }
        return toAjax(elevatorInfoService.updateElevatorInfo(elevatorInfo));
    }
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<ElevatorInfo> util = new ExcelUtil<ElevatorInfo>(ElevatorInfo.class);
        List<ElevatorInfo> elevatorInfoList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = elevatorInfoService.importData(elevatorInfoList, updateSupport, operName);
        return success(message);
    }

    /**
     * 删除电梯信息
     */
    @PreAuthorize("@ss.hasPermi('system:info:remove')")
    @Log(title = "电梯信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{elevatorIds}")
    public AjaxResult remove(@PathVariable Long[] elevatorIds)
    {
        return toAjax(elevatorInfoService.deleteElevatorInfoByElevatorIds(elevatorIds));
    }


}
